﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;
using SharePoint.Orm.Helpers;

namespace SharePoint.Orm.Metal {
	public class DefaultNameRewriter : INameRewriter {
		public string ListNamePrefix { get; set; }
		public string ListNameSuffix { get; set; }
		public string ContentTypeNamePrefix { get; set; }
		public string ContentTypeNameSuffix { get; set; }

		public DefaultNameRewriter() {
			ListNamePrefix = "";
			ListNameSuffix = "";
			ContentTypeNamePrefix = "";
			ContentTypeNameSuffix = "";
		}

		public virtual string ToContentTypeName(SPContentType contentType, string overrideTitle) {
			if (overrideTitle != null) {
				return ContentTypeNamePrefix + ToTypeName(overrideTitle) + ContentTypeNameSuffix;
			}
			return ContentTypeNamePrefix + ToTypeName(contentType.Name) + ContentTypeNameSuffix;
		}

		public virtual string ToListName(SPList list) {
			return ListNamePrefix + ToTypeName(list.Title) + ListNameSuffix;
		}

		public virtual string ToFieldName(SPField field) {
			return ToTypeName(field.StaticName);
		}

		public virtual string ToTypeName(string name) {
			name = SPNameHelper.Decode(name);
			name = Regex.Replace(name, "[^a-zA-Z0-9]", " ");
			StringBuilder result = new StringBuilder();
			bool lastCharSpace = false;
			bool firstCharHit = false;
			for (int i = 0; i < name.Length; i++) {
				char ch = name[i];
				if (ch == ' ') {
					lastCharSpace = true;
				} else {
					if (!firstCharHit && char.IsDigit(ch)) {
						continue;
					}

					firstCharHit = true;
					if (lastCharSpace) {
						lastCharSpace = false;
						ch = char.ToUpperInvariant(ch);
					}
					result.Append(ch);
				}
			}
			return result.ToString();
		}
	}
}
